package top.hcode.hoj.service;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author orangej
 * @since 2025/2/19
 */
@Component
@RequiredArgsConstructor
public class LockService {
    private final StringRedisTemplate redisTemplate;

    public boolean tryLock(String key, int seconds) {
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(key, "1", seconds, TimeUnit.SECONDS));
    }

    public boolean isLocked(String key) {
        return redisTemplate.hasKey(key);
    }

    public void releaseLock(String key) {
        redisTemplate.delete(key);
    }
}
